package interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import po.Manager;
import po.User;
import utils.SessionString;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//拦截器，进行非登录用户的监控拦截
public class UserLoginInterceptor implements HandlerInterceptor {
    //实现三个方法
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //获取URL
        StringBuffer url = httpServletRequest.getRequestURL();
        //进行登录拦截
        if(url.indexOf("/userLogin.action")>=0){
            return true;
        }
        //获取session会话
        HttpSession session = httpServletRequest.getSession();
        User user = (User) session.getAttribute(SessionString.USER_SESSION);
        Manager manager = (Manager) session.getAttribute(SessionString.Manager_SESSION);
        //数据判断
        if(user != null || manager != null){
            return true;
        }
        //不符合那就进行提示
        httpServletRequest.setAttribute("msg","您还未登录，请先登录");
        httpServletRequest.getRequestDispatcher("index.jsp").forward(httpServletRequest,httpServletResponse);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
